<?php

namespace Formax\Paginator;

class QueryBuilder extends \Phalcon\Paginator\Adapter\QueryBuilder
{

    public function getPaginate()
    {
        $paginate = parent::getPaginate();

        $builder = $this->getQueryBuilder();

        // 解决 query builder 中存在 group by 时的统计不准确的 bug
        // @link https://github.com/phalcon/cphalcon/issues/2411
        if ($group = $builder->getGroupBy()) {
            $result = $builder->columns('count(distinct ' . $group . ') as total')
                ->groupBy(null)
                ->getQuery()
                ->execute()
                ->getFirst();
            $paginate->total_items = $result->total;
            $paginate->total_pages = ceil($paginate->total_items / $this->getLimit());
        }

        return $paginate;
    }

}
